package com.example.baselibs.net.interceptor;


import com.example.baselibs.Constant.UserConstant;
import com.example.baselibs.net.RetrofitManager;
import com.example.baselibs.net.service.UserApi;
import com.example.baselibs.utils.localsp.SPLocalSave;
import com.orhanobut.logger.Logger;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * 同步登录没有完善
 * Created by Administrator on 2017/1/9.
 */
public class TokenInterceptor implements Interceptor {
    private static final Charset UTF8 = Charset.forName("UTF-8");

    @Override
    public synchronized Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        HttpUrl.Builder authorizedUrlBuilder = chain.request().url()
                .newBuilder()
                .addQueryParameter("token", "LongChinal1Ma-" + SPLocalSave.getInstance().getString(UserConstant.USER_ID));
        Request newRequest = request.newBuilder()
                .method(request.method(), request.body())
                .url(authorizedUrlBuilder.build())
                .build();
        Response originalResponse = chain.proceed(newRequest);

        /**通过如下的办法曲线取到请求完成的数据
         *
         * 原本想通过  originalResponse.body().string()
         * 但是使用过一次后，后面的body()取出的内容都为空
         *
         * 然后去看了okhttp的源码,找到了这个曲线方法,取到请求完成的数据后,根据特定的判断条件去判断token过期
         */
        ResponseBody responseBody = originalResponse.body();
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        Buffer buffer = source.buffer();
        Charset charset = UTF8;
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            charset = contentType.charset(UTF8);
        }

        String bodyString = buffer.clone().readString(charset);
//        LogUtils.d("TokenInterceptor", bodyString);
        return getNewToken(originalResponse, bodyString, chain, newRequest);
    }

    /**
     * 同步请求方式，获取刷新的Token
     *
     * @return
     */
    private Response getNewToken(Response originalResponse, String bodyString, Chain chain, Request newRequest) throws IOException {
        boolean login = false;
        String data = null;
        try {
            JSONObject jsonObject = new JSONObject(bodyString);
            login = jsonObject.getBoolean("login");
            data = jsonObject.getString("data");
            if (data.equals("用户帐号密码不对！")) return originalResponse;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (!login) {
            Logger.d("TokenInterceptor", "登录过期，正在重新登录");
            Map<String, String> map = new HashMap<>();
            map.put("D[USER_ID]", SPLocalSave.getInstance().getString(UserConstant.USER_ID));
            map.put("D[PASSWORD]", SPLocalSave.getInstance().getString(UserConstant.PASSWORD));
            map.put("T", "login");
            RetrofitManager.getInstance().getUserApiService(UserApi.class).synclogin(map).subscribe();
            originalResponse.body().close();
            return chain.proceed(newRequest);
        }
        return originalResponse;
    }
}
